package com.sly.fuxi.rabbitmq.producer;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author SLY
 * @date 2025/2/16
 */
@RestController
@RequestMapping("/rabbitmq")
public class RabbitMQProducer {

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 发送消息
     *
     * @param message    消息
     * @param exchange   交换机
     * @param routingKey routingKey
     * @return Object
     * @author SLY
     * @date 2025/2/16
     */
    @RequestMapping("/sendMessage")
    public Object sendMessage(String message, String exchange, String routingKey) {
        if (routingKey == null) {
            routingKey = "";
        }
        amqpTemplate.convertAndSend(exchange, routingKey, message);
        return "success";
    }

    /**
     * 发送延时消息
     *
     * @param message    消息
     * @param exchange   交换机
     * @param routingKey routingKey
     * @param delay      延时(毫秒)(最大为2147483647 )
     * @return Object
     * @author SLY
     * @date 2025/2/16
     */
    @RequestMapping("/sendDelayMessage")
    public Object sendDelayMessage(String message, String exchange, String routingKey, Integer delay) {
        if (routingKey == null) {
            routingKey = "";
        }

        // 消息后处理器，用于设置消息的延时时间
        MessagePostProcessor messagePostProcessor = message1 -> {
            // 设置消息的持久化模式
            message1.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            // 设置消息的延时时间，单位为毫秒
            message1.getMessageProperties().setHeader("x-delay", delay);
            return message1;
        };

        amqpTemplate.convertAndSend(exchange, routingKey, message, messagePostProcessor);
        return "success";
    }
}
